package com.gateway.video.rtsp.server.sdp;

import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import java.util.Arrays;

@Slf4j
public class SdpServerCodec {
    private static final int CTRL = 10;

    /**
     * sdp协议 格式 key=value CTRL
     *
     * @param buffer
     * @param sdpKeys   扩展sdp协议 key
     * @param sdpValues 扩展sdp协议 value
     * @return
     */
    public static ByteBuf encode(ByteBuf buffer, String[] sdpKeys, String[] sdpValues) {
        buffer.writeByte(CTRL);

        String[] keys = {SdpConstants.V, SdpConstants.O, SdpConstants.S, SdpConstants.I, SdpConstants.C, SdpConstants.T,
                SdpConstants.M, SdpConstants.B, SdpConstants.A, SdpConstants.A, SdpConstants.A, SdpConstants.A, SdpConstants.A, SdpConstants.A};

        String[] values = {"0", "- 16450650362115136848 16450650362115136848 in IP4 192.168.45.1", "Unnamed", "N/A", "IN IP4 0.0.0.0", "0 0",
                "video 0 RTP/AVP 96", "RR:0", "tool:vlc 3.0.14", "recvonly", "charset:UTF-8", "rtpmap:96 H265/90000", "framerate:25", "control:*"};

        if (sdpKeys != null && sdpValues != null && sdpKeys.length == sdpValues.length) {
            keys = Arrays.copyOf(keys, keys.length + sdpKeys.length);
            System.arraycopy(sdpKeys, 0, keys, sdpKeys.length, keys.length);

            values = Arrays.copyOf(values, values.length + sdpValues.length);
            System.arraycopy(sdpValues, 0, values, sdpValues.length, values.length);
        }

        for (var i = 0; i < keys.length; i++) {
            var value = keys[i] + "=" + values[i];
            buffer.writeBytes(value.getBytes());
            buffer.writeByte(CTRL);
        }

        if (log.isDebugEnabled()) {
            log.debug("Video server parse sdp \r\n kes {} \r\n values {}", keys, values);
        }
        return buffer;
    }
}
